package servlet;

import com.alibaba.fastjson2.JSON;
import entity.User;
import service.UserService;
import service.impl.UserServiceImp;
import utils.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/User1Servlet")
public class User1Servlet extends HttpServlet {
    UserService userService = new UserServiceImp();

    /**
     * 根据id查询
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        String id = req.getParameter("id");
        User user = userService.getById(Integer.parseInt(id));
        PrintWriter writer = resp.getWriter();
        writer.println(JSON.toJSONString(user));
        writer.flush();
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        //接收前端值
        String username = req.getParameter("username");
        String id = req.getParameter("id");
        String gender = req.getParameter("gender");
        String phone = req.getParameter("phone");
        Date birthday = RequestUtil.parseDate(req, "birthday", null, "yyyy-MM-dd");

        User user = new User();
        user.setBirthday(birthday);
        user.setUsername(username);
        user.setGender(Integer.parseInt(gender));
        user.setIs_deleted(RequestUtil.parseInt(req, "is_deleted", null));
        user.setPhone(phone);
        user.setId(Integer.parseInt(id));

        Integer count = userService.updateById(user);

        Map map = new HashMap();
        PrintWriter writer = resp.getWriter();
        if (count > 0) {
            map.put("code", 1);
            map.put("msg", "修改成功");
        } else {
            map.put("code", 0);
            map.put("msg", "修改失败");
        }
        writer.println(JSON.toJSONString(map));
        writer.flush();
        writer.close();
    }


}
